//
//  AppDelegate.swift
//  TimMusic
//
//  Created by nkl on 2024/9/29.
//

import BackgroundTasks
import TSVideoKit
import UIKit
import WidgetKit

@main
class AppDelegate: UIResponder, UIApplicationDelegate {
    var window: UIWindow?

    var downloader: TSNewDownloadManager?

    func application(_ application: UIApplication, didFinishLaunchingWithOptions launchOptions: [UIApplication.LaunchOptionsKey: Any]?) -> Bool {
        // Override point for customization after application launch.
        window = UIWindow(frame: UIScreen.main.bounds)
        window?.backgroundColor = .white
        let rootVc = SpashViewController()
        window?.rootViewController = rootVc
        window?.makeKeyAndVisible()
        initTSVideoKit()
        return true
    }

    func initTSVideoKit() {
        var config = TSConfiguration.default
        config.needLog = true
        TSVideoOperator.shared.loadWithConfiguration(config: config)
        downloader = TSVideoOperator.shared.downloadManager
    }

 
    func application(_ application: UIApplication, handleOpen url: URL) -> Bool {
        handleSchemeUrl(url: url)
        return true
    }

    private func handleMusicControlTask(task: BGAppRefreshTask) {
        // 处理音乐控制逻辑
        let action = getActionFromSharedData()
        switch action {
        case "pause":
            print("pause")
        case "next":
            print("next")
        case "previous":
            print("previous")
        default:
            break
        }

        // 确保任务完成
        task.setTaskCompleted(success: true)
    }

    private func getActionFromSharedData() -> String? {
        let sharedDefaults = UserDefaults(suiteName: "group.yourapp")
        return sharedDefaults?.string(forKey: "musicControl")
    }

    func handleSchemeUrl(url: URL) {
        print(url.absoluteString)
    }
    
    func applicationWillTerminate(_ application: UIApplication) {
        updateWidgetPlayStatus(isPlaying: false)
    }
    
    
    func updateWidgetPlayStatus(isPlaying:Bool) {
        let sharedDefaults = UserDefaults(suiteName: TimeGroupName)
        sharedDefaults?.set(isPlaying, forKey: "widgetPlay")
        WidgetCenter.shared.reloadAllTimelines()
    }

}
